package com.financing.wap.web.controller.api;


import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.wap.common.BizEnums;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.BankCardDTO;
import com.financing.wap.dto.FpBiddingReceiptDTO;
import com.financing.wap.dto.FpPaymentDTO;
import com.financing.wap.dto.FpYouDanAmountDetailDTO;
import com.financing.wap.dto.OrderDTO;
import com.financing.wap.dto.ProductDetailPageDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IBankCardService;
import com.financing.wap.service.ICheckCodeService;
import com.financing.wap.service.ICommonService;
import com.financing.wap.service.IFpBiddingReceiptService;
import com.financing.wap.service.IOrderService;
import com.financing.wap.service.IPaymentService;
import com.financing.wap.service.IProductService;
import com.financing.wap.service.ISmsNewService;
import com.financing.wap.service.ISmsService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.IYouDanAmountDetailService;
import com.financing.wap.service.payment.biz.PaymentBizService;
import com.financing.wap.util.BasicUtils;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.IPUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.SecureUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

/**
 * 通用支付模块
 * @author lisu
 *
 */
@Controller
@RequestMapping("/api/payCommon")
public class PaymentCommonController extends BaseController{
	
	Logger logger = Logger.getLogger(getClass());
	private SimpleDateFormat sd = new SimpleDateFormat(
			BizEnums.CommonEnums.JUYOUBAO_DATE_PATTERN);// 聚友投平台日期格式
	
	/**
	 * 支付相关服务（包含业务逻辑处理的服务）
	 */
	@Autowired
	private PaymentBizService paymentBaofooBizService;
	
	@Autowired
	private IUserService userService;

	@Autowired
	private IBankCardService bankCardServiceImpl;
	
	@Autowired
	private ICheckCodeService checkCodeServiceImpl;
	
	@Autowired
	IFpBiddingReceiptService fpBiddingReceiptService;//竞价服务

	@Autowired
	private IOrderService orderService;//订单服务
	
	@Autowired
	private ICommonService commonServiceImpl;// 公共服务
	
	@Autowired
	private IYouDanAmountDetailService youDanAmountDetailServiceImpl;//有单金额明细表 服务
	
	@Autowired
	private IPaymentService paymentServiceImpl;// 支付流水服务
	
	@Autowired
	private IProductService  productService;//产品服务
	
	@Autowired
	public ISmsNewService smsNewService;  //短信服务
	
	@Resource(name="EmailSendServiceImp")
	private MailSenderService mailSenderService;//邮件服务
	
	String biddingProductPhoneTo=PropertiesUtils.getValue("biddingProduct.phone.to");

	String biddingProductEmailTo=PropertiesUtils.getValue("biddingProduct.email.send.to");
	
	String biddingProductEmailCopyTo=PropertiesUtils.getValue("biddingProduct.email.send.copy.to");
	
	//提现发送给财务的  邮件和短信  
	String withdrawalsPhoneTo=PropertiesUtils.getValue("withdrawals.phone.to");
	String withdrawalsEmailTo=PropertiesUtils.getValue("withdrawals.email.send.to");
	String withdrawalsEmailCopyTo=PropertiesUtils.getValue("withdrawals.email.send.copy.to");
	
	/**
	 * 用户绑卡, 实名认证. 绑卡请求第一步
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/invokebindbankcard")
	@ResponseBody
	public synchronized ResultMap invokebindbankcard(ModelMap model, HttpServletRequest request, HttpServletResponse response){
		
		ResultMap result = new ResultMap();

		if( logger.isInfoEnabled() ){
			logger.info("invokebindbankcard request begin!");
		}
		
		try {
			
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			String userId = loginUser.getId();
			String username = request.getParameter("username");//持卡人姓名
			String idcardno = request.getParameter("idcardno");//身份证号
			String cardno = request.getParameter("cardno");//银行卡号cardno.replace(" ", "")
				   cardno = StringUtils.trim(cardno).replace(" ", "");
			String phone = request.getParameter("phone");//注册手机号
			//String bankname = request.getParameter("bankname");//银行名称，统一使用“sfa”支付商的
			//String bankcode = request.getParameter("bankcode");//银行编码，统一使用“sfa”支付商的
			String payPlat = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//默认-支付厂商标识（宝付）
			
			//检查参数是否有空值
			if(BasicUtils.isEmpty(username, cardno, phone, idcardno) || userId== null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			
			//4，检查用户状态
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			
			//------------   原来的判断场景  ------------------------------
			/*
			 * 场景：
			 * 同一个用户A，银行卡 C ，身份证 P 在【易宝】渠道已经绑卡；
			 * 系统将该银行的支付渠道变更为【宝付】
			 * 情况1： 用户B 使用 银行卡 C 来绑卡，应该提示银行卡已经被别的用户绑定了；
			 * 情况2： 用户B 使用 身份证 P 来绑卡，应该提供该证件已经被其他用户绑定；
			 * 情况3： 用户A 使用 C2 来绑卡，应该提水 此前已经绑定过C，只能继续用C，或者联系客服；
			 * 情况4： 用户A 使用 C，P来绑卡，走宝付，绑卡成功；此时检查，绑卡记录数 
			 */
			/*if( StringUtils.isNotEmpty( userInfo.getDefBingingCrad() ) 
					 && 
					!StringUtils.equals(userInfo.getDefBingingCrad(), cardno))
				{
					 
					 * 换支付商需要再绑卡，会再次操作绑卡，但是：
					 * 新绑卡时必须是原来已经绑定过的银行卡，否则报错
					 
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_TIED_CARD);
					result.setMessage("您此前已绑定了尾号为"
							+BasicUtils.ensitiveAcctNo(userInfo.getDefBingingCrad())+"的银行卡，如需换卡绑定请联系聚友投客服！");
					return result;
				}
				
				//2, 检查银行卡是否已经被其他用户绑定过
				Map<String,Object> map = new HashMap<String, Object>(); 
				map.put("userId", userId);
				map.put("bankCard", cardno);
				
				int count = bankCardServiceImpl.countOtherUserBindBankCard(map);//自己绑定时，记录数为0
				 
				if( count > 0 )
				{
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_BANKCARD_BY_OTHER);
					result.setMessage("该银行卡已被他人绑定");
					logger.warn("当前用户<"+userId+">正在绑定尾号为<"+BasicUtils.ensitiveAcctNo(cardno)+">的银行卡，但该银行卡已被其它用户绑定！");
					return result;
				}
				
				
				//3, 检查身份证是否被别的用户绑定
				UserDTO testUser = userService.loadByPaperNo(idcardno);
				if( testUser != null 
						&& 
					testUser.getId().intValue()!=userId.intValue())//持有该身份证的用户不是当前绑卡用户
				{
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_IDCARD_BY_OTHER);
					result.setMessage("该身份证已被绑定到其它用户");
					logger.warn("当前用户<"+userId+">正在使用身份证<"+idcardno+">绑卡，但是已被其它用户<"+testUser.getId()+">绑定");
					return result;
				}
				
				//检查是否已经在该支付渠道绑定过该银行卡
				boolean flag = bankCardServiceImpl.checkBankcardAndPayplatIsBinded(cardno, payPlat);
				if(flag){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_BANKCARD_BOUND);
					result.setMessage("您的银行卡已绑定过");
					return result;
				}
				*/
			
			
			//------------   现在的判断场景   ------------------------------
			/*
			 * 场景：
			 * 用户A的银行卡唯一
			 * 用户B可以绑定用户A的银行卡
			 * 用户B可以绑定用户A的银行卡（包括身份证）
			 * 一个用户最多绑定3张卡
			 */
			if(userInfo.getBindingNum() != null && userInfo.getBindingNum() >= BizEnums.UserEnums.USER_CARD_NUMBER){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4016);
				result.setMessage("绑卡数量超出");
				return result;
			}
				
			//检查是否已经在该支付渠道绑定过该银行卡
			boolean flag = bankCardServiceImpl.checkBankcardAndPayplatIsBinded(cardno, payPlat,userId);
			if(flag){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_BANKCARD_BOUND);
				result.setMessage("您的银行卡已绑定过");
				return result;
			}
			
			if( logger.isInfoEnabled() ){
				logger.info("invokebindbankcard request paymentBaofooBizService!");
			}
			
			//组装绑卡请求参数
			Map<String,String> auth = new HashMap<String, String>();
			auth.put("identityid", userId.toString());
			auth.put("username", username);
			auth.put("idcardno", idcardno);
			auth.put("cardno", cardno.replace(" ", ""));//去除卡号的空白
			auth.put("phone", phone);
			auth.put("userip", IPUtil.getRemoteHost(request));
			
			//真实绑卡请求发送-发送验证码
			Map<String,String> resultMap = new HashMap<String,String>();
			resultMap = paymentBaofooBizService.invokebindbankcard(auth);
			if("SUCCESS".equals(resultMap.get("status"))){
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(resultMap.get("statusCode"));
			}
			
			//添加支付商信息
			result.setAttribute("payplat", payPlat);
			
			if( logger.isInfoEnabled() ){
				logger.info("invokebindbankcard request end!");
			}
		} catch (Exception e) {
			logger.error("invokebindbankcard error:",e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 用户绑卡, 实名认证. 绑卡请求第二步
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/confirmbindbankcard")
	@ResponseBody
	public synchronized ResultMap confirmbindbankcard(ModelMap model,
			HttpServletRequest request, HttpServletResponse response){
		
		ResultMap result = new ResultMap();
		
		if( logger.isInfoEnabled() ){
			logger.info("confirmbindbankcard request begin!");
		}
		
		try {
			
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();
			


			String requestid =  request.getParameter("requestid");//绑卡请求唯一编号
			String validatecode =  request.getParameter("validatecode");//短信验证码
			String username =  request.getParameter("username");//用户名
			String idcardno =  request.getParameter("idcardno");//身份证号
			String cardno =  request.getParameter("cardno");//银行卡号
			String phone =  request.getParameter("phone");//注册手机号
			String bankname =  request.getParameter("bankname");//银行名称，统一使用“聚友投”支付商的
			String bankcode =  request.getParameter("bankcode");//银行编码，统一使用“聚友投”支付商的
			String binded =  request.getParameter("binded");//表示易宝支付中已经绑定过卡，只是聚友投平台未绑定过
			String payPlat = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//支付厂商标识（宝付）
			

	/*		String requestid =  request.getParameter("requestid");//绑卡请求唯一编号
			String validatecode =  request.getParameter("validatecode");//短信验证码
			String username =  "李苏";
			String idcardno =  request.getParameter("idcardno");//身份证号
			String cardno =  request.getParameter("cardno");//银行卡号
			String phone =  request.getParameter("phone");//注册手机号
			String bankname =  "平安银行";
			String bankcode =  "PAB";
			String binded =  request.getParameter("binded");//表示易宝支付中已经绑定过卡，只是聚友投平台未绑定过
			String payPlat = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//支付厂商标识（宝付）
*/			
			//1、检查参数是否有空值
			if(BasicUtils.isEmpty( username, cardno, phone, idcardno)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			//2、，检查用户状态
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}	
			
			//------------   原来的判断场景  ------------------------------
			/*
			 * 场景：
			 * 同一个用户A，银行卡 C ，身份证 P 在【易宝】渠道已经绑卡；
			 * 系统将该银行的支付渠道变更为【宝付】
			 * 情况1： 用户B 使用 银行卡 C 来绑卡，应该提示银行卡已经被别的用户绑定了；
			 * 情况2： 用户B 使用 身份证 P 来绑卡，应该提供该证件已经被其他用户绑定；
			 * 情况3： 用户A 使用 C2 来绑卡，应该提水 此前已经绑定过C，只能继续用C，或者联系客服；
			 * 情况4： 用户A 使用 C，P来绑卡，走宝付，绑卡成功；此时检查，绑卡记录数 
			 */
			/*if( StringUtils.isNotEmpty( userInfo.getDefBingingCrad() ) 
					 && 
					!StringUtils.equals(userInfo.getDefBingingCrad(), cardno))
				{
					 
					 * 换支付商需要再绑卡，会再次操作绑卡，但是：
					 * 新绑卡时必须是原来已经绑定过的银行卡，否则报错
					 
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_TIED_CARD);
					result.setMessage("您此前已绑定了尾号为"
							+BasicUtils.ensitiveAcctNo(userInfo.getDefBingingCrad())+"的银行卡，如需换卡绑定请联系聚友投客服！");
					return result;
				}
				
				//2, 检查银行卡是否已经被其他用户绑定过
				Map<String,Object> map = new HashMap<String, Object>(); 
				map.put("userId", userId);
				map.put("bankCard", cardno);
				
				int count = bankCardServiceImpl.countOtherUserBindBankCard(map);//自己绑定时，记录数为0
				 
				if( count > 0 )
				{
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_BANKCARD_BY_OTHER);
					result.setMessage("该银行卡已被他人绑定");
					logger.warn("当前用户<"+userId+">正在绑定尾号为<"+BasicUtils.ensitiveAcctNo(cardno)+">的银行卡，但该银行卡已被其它用户绑定！");
					return result;
				}
				
				
				//3, 检查身份证是否被别的用户绑定
				UserDTO testUser = userService.loadByPaperNo(idcardno);
				if( testUser != null 
						&& 
					testUser.getId().intValue()!=userId.intValue())//持有该身份证的用户不是当前绑卡用户
				{
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_IDCARD_BY_OTHER);
					result.setMessage("该身份证已被绑定到其它用户");
					logger.warn("当前用户<"+userId+">正在使用身份证<"+idcardno+">绑卡，但是已被其它用户<"+testUser.getId()+">绑定");
					return result;
				}
				
				//检查是否已经在该支付渠道绑定过该银行卡
				boolean flag = bankCardServiceImpl.checkBankcardAndPayplatIsBinded(cardno, payPlat);
				if(flag){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_BANKCARD_BOUND);
					result.setMessage("您的银行卡已绑定过");
					return result;
				}
				*/
			
			
			//------------   现在的判断场景   ------------------------------
			/*
			 * 场景：
			 * 用户A的银行卡唯一
			 * 用户B可以绑定用户A的银行卡
			 * 用户B可以绑定用户A的银行卡（包括身份证）
			 * 一个用户最多绑定3张卡
			 */
			if(userInfo.getBindingNum() != null && userInfo.getBindingNum() >= BizEnums.UserEnums.USER_CARD_NUMBER){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4016);
				result.setMessage("绑卡数量超出");
				return result;
			}
			
				
			//检查是否已经在该支付渠道绑定过该银行卡 ---一个卡只能绑定一次
			boolean flag = bankCardServiceImpl.checkBankcardAndPayplatIsBinded(cardno, payPlat,null);
			if(flag){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_BANKCARD_BOUND);
				result.setMessage("您的银行卡已绑定过");
				return result;
			}
				
			//3、，手机验证码---当验证码不为空的时候就验证
			if(StringUtils.isNotBlank(validatecode)){
				if(checkCodeServiceImpl.CheckCodeSwitch()){
					Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time"));
					//验证码超时
					if(checkOtpCodeTimeOut(phone,activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){
						result.setStatus(ResultMap.STATUS.FAILE);
						result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
						result.setMessage("手机验证码超时！");
						return result;
						
					};
					ResultMap resultOtp = checkOtpCode(phone,validatecode);
					if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
						result.setStatus(resultOtp.getStatus());
						result.setStatusCode(resultOtp.getStatusCode());
						result.setMessage(resultOtp.getMessage());
						return result;
					}
				}
			}
			if( logger.isInfoEnabled() ){
				logger.info("confirmbindbankcard request paymentBaofooBizService!");
			}
			
			//组装绑卡请求参数
			Map<String,String> auth = new HashMap<String, String>();
			auth.put("identityid", userId.toString());//用户编码
			auth.put("username", username);//持卡人姓名
			auth.put("idcardno", idcardno);//身份证号
			auth.put("cardno", cardno.replace(" ", ""));//银行卡号
			auth.put("phone", phone);//手机号
			auth.put("bankname", bankname);//银行名称
			auth.put("bankcode", bankcode);//银行编码
			auth.put("binded", binded);//是否易宝中已经绑定过卡片，只是聚友投平台未绑定过而已
			auth.put("requestid", requestid);//绑定请求号
			auth.put("validatecode", validatecode);//短信验证码
			
			//确认绑卡
			Map<String,String> resultMap = new HashMap<String,String>();
			resultMap = paymentBaofooBizService.confirmbindbankcard(auth);
			if("SUCCESS".equals(resultMap.get("status"))){
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("cardId", resultMap.get("cardId"));
				if( logger.isInfoEnabled() ){
					logger.info("confirmbindbankcard request paymentBaofooBizService SUCCESS!");
				}
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("errorMsg", resultMap.get("errorMsg"));
				if( logger.isInfoEnabled() ){
					logger.info("confirmbindbankcard request paymentBaofooBizService FAILE!");
				}
			}
			
			if( logger.isInfoEnabled() ){
				logger.info("confirmbindbankcard request end!");
			}
		} catch (Exception e) {
			log.error("confirmbindbankcard error!",e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	
	/**
	 * 用户 解除绑卡
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/releaseBindbankcard")
	@ResponseBody
	public synchronized ResultMap releaseBindbankcard(ModelMap model,
			HttpServletRequest request, HttpServletResponse response){
		
		ResultMap result = new ResultMap();
		
		if( logger.isInfoEnabled() ){
			logger.info("releaseBindbankcard request begin!");
		}
		
		try {
			
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();
			


			//String tradePwd =  request.getParameter("tradePwd");//交易密码
			String payPlat = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//支付厂商标识（宝付）
			String cardId = request.getParameter("cardId");//卡id
			Integer cardId_ = null;
			
			//1、检查参数是否有空值
			if(BasicUtils.isEmpty( cardId)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			try {
				cardId_ = Integer.valueOf(cardId) ;
			} catch (Exception e) {
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			//2、，检查用户状态
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}		
			
			String bankCard = userInfo.getDefBingingCrad();
			if(StringUtils.isEmpty(bankCard)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4007);
				result.setMessage("还未绑定银行卡");
				return result;
			}
			
			//3、查询 根据cardId_ 查询银行卡
			BankCardDTO bankCardDTOView = new BankCardDTO();
			bankCardDTOView.setId(cardId_);
			bankCardDTOView.setUserId(userId);
			bankCardDTOView = bankCardServiceImpl.queryBankCard(bankCardDTOView);
			
			if(bankCardDTOView == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4017);
				result.setMessage("该银行卡不存在");
				return result;
			}
			
			String cardno = bankCardDTOView.getCardNumber();//银行账号
			
			BankCardDTO bankCardDTO  = new BankCardDTO();
			bankCardDTO.setCardNumber(cardno);
			bankCardDTO.setUserId(userId);
			bankCardDTO.setPayPlat(payPlat);
			bankCardDTO.setIsDefault(BizEnums.UserEnums.USER_BINDED_CARD_DEFAULT);
			List<BankCardDTO> bankCardDTOList = bankCardServiceImpl.queryBankCardList(bankCardDTO);
			
			if(bankCardDTOList!=null && bankCardDTOList.size()>0){
				bankCardDTO = bankCardDTOList.get(0);
				bankCardDTO.setIsDefault(BizEnums.UserEnums.USER_BINGDING_CARD_OFF);//修改为 2-已解绑
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4007);
				result.setMessage("还未绑定银行卡");
				return result;
			}
			bankCardDTO.setReleaseTime(new Date());
			DTOdateSetUtil.setUpdateInfo(bankCardDTO);
			
			
			//2)根据“用户编号、注册手机号”清理用户注册表（user）绑定银行卡痕迹
			long bindingNum = userInfo.getBindingNum();
			if(bindingNum>1){
				--bindingNum;
				userInfo.setBindingNum(bindingNum);//绑定数(binding_num)减一
			}else{
				userInfo.setBindingNum(0l);//绑定数0
				userInfo.setDefBingingCrad(null);//清空默认卡(def_binging_crad)、
				userInfo.setDefCardBankCode(null);
				userInfo.setIsRealNmae(BizEnums.UserEnums.USER_REALNAME_NO);//实名认证标志(is_real_nmae)修改为“0未认证”、
				userInfo.setRealDate(null);//清空实名认证日期(real_date)、
				userInfo.setRealTime(null);//清空实名认证时间(real_time)、
				userInfo.setRealRetMsg(null);//清空实名认证响应(real_ret_msg)、
				userInfo.setRealPaperType(null);//清空证件类型(real_paper_type)、
				userInfo.setRealPaperNo(null);//清空证件号(real_paper_no)；
			}

			DTOdateSetUtil.setUpdateInfo(userInfo);
			
			if( logger.isInfoEnabled() ){
				logger.info("releaseBindbankcard request db!");
			}
			
			commonServiceImpl.releaseBindbankcard(bankCardDTO, userInfo);
			
			
			if( logger.isInfoEnabled() ){
				logger.info("releaseBindbankcard request end!");
			}
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("releaseBindbankcard error!",e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	
	
	/**
	 * 用户发送支付请求
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return 
	 * {
	 * retCode=1
	 * retMessage=""
	 * needJump=""
	 * }
	 */
	@RequestMapping("/sendPayRequestYJ")
	@ResponseBody
	public synchronized ResultMap sendPayRequestYJ(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();

		if( logger.isInfoEnabled() ){
			logger.info("sendSMSRequestBZJ request begin!");
		}
		
		try {
			
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			String userId = loginUser.getId();
			
			//获取前端传入的数据
			String orderId = request.getParameter("orderId");//订单号
			//String tradePwd = request.getParameter("tradePwd");//交易密码
			String smsCode = request.getParameter("smsCode");//短信验证码
			//String payPlat = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//默认-支付厂商标识（宝付）
			String cardId = request.getParameter("cardId");//卡ID
			
			//1、检查参数是否有空值
			if(BasicUtils.isEmpty( cardId)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			try {
				Integer.valueOf(cardId) ;
			} catch (Exception e) {
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			//检查参数是否有空值
			if(BasicUtils.isEmpty(orderId,smsCode) || userId== null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			//查询订单
			OrderDTO orderDTO = orderService.getOrder(orderId);

			//1, 检查订单是否存在     且是未支付状态
			if(orderDTO==null || orderDTO.getoYouDanRebate() == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("业务对象不存在");
				return result;
			}
			
			//TODO  订单状态
			
			//2、，检查用户状态
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
/*			if(StringUtils.isEmpty(userInfo.getTradePwd())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4008);
				result.setMessage("交易密码不存在");
				return result;
			}*/
			
			
			String bankCard = userInfo.getDefBingingCrad();
			if(StringUtils.isEmpty(bankCard)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4007);
				result.setMessage("还未绑定银行卡");
				return result;
			}
			//TODO 3、判断用户状态
			
			
			//4, 检查用户输入的交易密码是否正确
			/*if(!StringUtils.equals(userInfo.getTradePwd(), SecureUtil.MD5EncryptAndBase64(tradePwd)) ){
				long errTimes = userInfo.getTradeErrTimes();//输入的交易密码错误次数
				errTimes = errTimes + 1;//本次错误追加1次
				//累计交易密码错误次数
				userInfo.setTradeErrTimes(errTimes) ;
				
				logger.info( "已错误"+errTimes+"次，还有"+(BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES-errTimes)+"次机会将被锁定！" );
				if(errTimes >= BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES){
					//错误次数超限
					logger.warn("user<"+userId+"> trade password lock");
					userInfo.setFaStatus("04");
				}
				userService.updateUser(userInfo);

				result.setAttribute("remainingErrorNumber", BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES-errTimes);
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4011);
				result.setMessage("交易密码不正确");
				return result;
			}
			
			//检查如果用户的交易密码累计次数大于0，则重置为0，因为本次输入正确了
			if(userInfo.getTradeErrTimes()>0){
				userInfo.setTradeErrTimes(0l);
				userService.updateUser(userInfo);
			}*/

			
				
			//成功通过校验
			if( logger.isInfoEnabled() ){
				logger.info("sendSMSRequestBZJ request paymentBaofooBizService!");
			}	

			//支付请求参数
			Map<String, String> payRequest = new HashMap<String, String>();
			payRequest.put("orderid", orderId);//订单编码
			payRequest.put("identityid", userId.toString());//用户唯一编码
			payRequest.put("smsCode", smsCode);//2016-01-18添加短信
			payRequest.put("cardId", cardId);//卡id

			//发送短信请求
			Map<String,String> resultMap = new HashMap<String,String>();
			resultMap = paymentBaofooBizService.sendPayRequestYJ(payRequest);
			if("SUCCESS".equals(resultMap.get("status"))){
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				
				//返回-支付金额、支付内容、支付金额、支付方式、交易时间、交易单号
				result.setAttribute("amount", resultMap.get("amount"));
				result.setAttribute("content", resultMap.get("content"));
				result.setAttribute("mode", resultMap.get("mode"));
				result.setAttribute("time", resultMap.get("time"));
				result.setAttribute("number", resultMap.get("number"));
				
				if( logger.isInfoEnabled() ){
					logger.info("sendSMSRequestBZJ request paymentBaofooBizService SUCCESS!");
				}
				
				/*支付请求成功 发送短信通知 */
				List<String> mobileList=new ArrayList<String>();
				mobileList.add(userInfo.getLoginName());
				
				String content="您尾号%s的卡片 %s支付佣金 RMB%s元，如有问题请拨打电话400-855-8085";
				content=String.format(content,StringUtil.encryptCardNumberPostFour(resultMap.get("cardNumber")),DateUtil.getString(new Date(),"HH:mm"),resultMap.get("amount"));
				
				smsNewService.sendSms(mobileList,content,"smsSendSwitch");
				
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("errorMsg", resultMap.get("errorMsg"));
				
				if( logger.isInfoEnabled() ){
					logger.info("sendSMSRequestBZJ request paymentBaofooBizService FAILE!");
				}
			}

			
		} catch (Exception e) {
			log.error("sendPayRequestBZJ error!",e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 用户发送支付请求-发送验证码
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return 
	 * {
	 * retCode=1
	 * retMessage=""
	 * needJump=""
	 * }
	 */
	@RequestMapping("/sendSMSRequestYJ")
	@ResponseBody
	public synchronized ResultMap sendSMSRequestYJ(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();

		if( logger.isInfoEnabled() ){
			logger.info("sendSMSRequestYJ request begin!");
		}
		
		try {
			
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			String userId = loginUser.getId();
			
			//获取前端传入的数据。
			String orderId = request.getParameter("orderId");//订单号
			String cardId = request.getParameter("cardId");//卡ID
			//String payPlat = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//默认-支付厂商标识（宝付）
			
			//1、检查参数是否有空值
			if(BasicUtils.isEmpty( cardId)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			try {
				Integer.valueOf(cardId) ;
			} catch (Exception e) {
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			//检查参数是否有空值
			if(BasicUtils.isEmpty(orderId) || userId== null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			//查询订单
			OrderDTO orderDTO = orderService.getOrder(orderId);

			//1, 检查订单是否存在     且是未支付状态
			if(orderDTO==null || orderDTO.getoYouDanRebate()== null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("业务对象不存在");
				return result;
			}
			
			//2、，检查用户状态
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			String bankCard = userInfo.getDefBingingCrad();
			if(StringUtils.isEmpty(bankCard)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4007);
				result.setMessage("还未绑定银行卡");
				return result;
			}
			
/*			if(StringUtils.isEmpty(userInfo.getTradePwd())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4008);
				result.setMessage("交易密码不存在");
				return result;
			}*/
			
			//TODO 3、判断用户状态

			//成功通过校验
			if( logger.isInfoEnabled() ){
				logger.info("sendSMSRequestYJ request paymentBaofooBizService!");
			}
				
			//支付请求参数
			Map<String, String> payRequest = new HashMap<String, String>();
			payRequest.put("orderid", orderId);//订单编码
			payRequest.put("identityid", userId.toString());//用户唯一编码
			payRequest.put("cardId", cardId);//卡id
			

			//发送短信请求
			Map<String,String> resultMap = new HashMap<String,String>();
			resultMap = paymentBaofooBizService.sendSMSRequestYJ(payRequest);
			if("SUCCESS".equals(resultMap.get("status"))){
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				
				if( logger.isInfoEnabled() ){
					logger.info("sendSMSRequestYJ request paymentBaofooBizService SUCCESS!");
				}
				
			}else{
				result.setStatus(STATUS.FAILE);
				result.setAttribute("errorMsg", resultMap.get("errorMsg"));
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				
				if( logger.isInfoEnabled() ){
					logger.info("sendSMSRequestYJ request paymentBaofooBizService FAILE!");
				}
			}

			
		} catch (Exception e) {
			log.error("sendSMSRequestYJ error!",e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	
	/**
	 * 用户发送支付请求-发送验证码
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return 
	 * {
	 * retCode=1
	 * retMessage=""
	 * needJump=""
	 * }
	 */
	@RequestMapping("/sendSMSRequestBZJ")
	@ResponseBody
	public synchronized ResultMap sendSMSRequestBZJ(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();

		if( logger.isInfoEnabled() ){
			logger.info("sendSMSRequestBZJ request begin!");
		}
		
		try {
			
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			String userId = loginUser.getId();
			
			//获取前端传入的数据。
			String orderId = request.getParameter("orderId");//订单号
			//String payPlat = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//默认-支付厂商标识（宝付）
			String cardId = request.getParameter("cardId");//卡id
			
			//1、检查参数是否有空值
			if(BasicUtils.isEmpty( cardId)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			try {
				Integer.valueOf(cardId) ;
			} catch (Exception e) {
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			//检查参数是否有空值
			if(BasicUtils.isEmpty(orderId) || userId== null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			FpBiddingReceiptDTO dto = new FpBiddingReceiptDTO();
			dto.setBiddingCode(orderId);
			dto = fpBiddingReceiptService.queryFpBiddingReceiptInfo(dto);
			
			//1, 检查订单是否存在
			if(dto==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("业务对象不存在");
				return result;
			}
			
			//2, 检查订单状态 是否已经支付
			if(BizEnums.BiddingReceiptEnums.FLAG_BAIL_YES.equals(dto.getFlagBail())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4013);
				result.setMessage("订单状态已经支付");
				return result;
			}
			
			//2、，检查用户状态
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			/*if(StringUtils.isEmpty(userInfo.getTradePwd())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4008);
				result.setMessage("交易密码不存在");
				return result;
			}*/
			
			String bankCard = userInfo.getDefBingingCrad();
			if(StringUtils.isEmpty(bankCard)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4007);
				result.setMessage("还未绑定银行卡");
				return result;
			}
			
			//TODO 3、判断用户状态
			
			//成功通过校验
			if( logger.isInfoEnabled() ){
				logger.info("sendSMSRequestBZJ request paymentBaofooBizService!");
			}
				
			//支付请求参数
			Map<String, String> payRequest = new HashMap<String, String>();
			payRequest.put("orderid", orderId);//订单编码
			payRequest.put("identityid", userId.toString());//用户唯一编码
			payRequest.put("cardId", cardId);//卡id

			//发送短信请求
			Map<String,String> resultMap = new HashMap<String,String>();
			resultMap = paymentBaofooBizService.sendSMSRequestBZJ(payRequest);
			if("SUCCESS".equals(resultMap.get("status"))){
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				
				if( logger.isInfoEnabled() ){
					logger.info("sendSMSRequestBZJ request paymentBaofooBizService SUCCESS!");
				}
				
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(resultMap.get("statusCode"));
				result.setAttribute("errorMsg", resultMap.get("errorMsg"));
				if( logger.isInfoEnabled() ){
					logger.info("sendSMSRequestBZJ request paymentBaofooBizService FAILE!");
				}
			}
			
		} catch (Exception e) {
			log.error("sendSMSRequestBZJ error!",e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 用户发送支付请求
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return 
	 * {
	 * retCode=1
	 * retMessage=""
	 * needJump=""
	 * }
	 */
	@RequestMapping("/sendPayRequestBZJ")
	@ResponseBody
	public synchronized ResultMap sendPayRequestBZJ(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();

		if( logger.isInfoEnabled() ){
			logger.info("sendSMSRequestBZJ request begin!");
		}
		
		try {
			
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			String userId = loginUser.getId();
			
			//获取前端传入的数据
			String orderId = request.getParameter("orderId");//订单号
			//String tradePwd = request.getParameter("tradePwd");//交易密码
			String smsCode = request.getParameter("smsCode");//短信验证码
			String cardId = request.getParameter("cardId");//短信验证码
			//String payPlat = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//默认-支付厂商标识（宝付）
			
			//1、检查参数是否有空值
			if(BasicUtils.isEmpty( cardId)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			try {
				Integer.valueOf(cardId) ;
			} catch (Exception e) {
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			//检查参数是否有空值
			if(BasicUtils.isEmpty(orderId,smsCode) || userId== null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			FpBiddingReceiptDTO dto = new FpBiddingReceiptDTO();
			dto.setBiddingCode(orderId);
			dto = fpBiddingReceiptService.queryFpBiddingReceiptInfo(dto);
			
			//1, 检查订单是否存在
			if(dto==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("业务对象不存在");
				return result;
			}
			
			//2, 检查订单状态 是否已经支付
			if(BizEnums.BiddingReceiptEnums.FLAG_BAIL_YES.equals(dto.getFlagBail())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4013);
				result.setMessage("订单状态已经支付");
				return result;
			}
			
			//2、，检查用户状态
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
/*			if(StringUtils.isEmpty(userInfo.getTradePwd())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4008);
				result.setMessage("交易密码不存在");
				return result;
			}*/
			
			
			String bankCard = userInfo.getDefBingingCrad();
			if(StringUtils.isEmpty(bankCard)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4007);
				result.setMessage("还未绑定银行卡");
				return result;
			}
			//TODO 3、判断用户状态
			
			
			//4, 检查用户输入的交易密码是否正确
			/*if(!StringUtils.equals(userInfo.getTradePwd(), SecureUtil.MD5EncryptAndBase64(tradePwd)) ){
				long errTimes = userInfo.getTradeErrTimes();//输入的交易密码错误次数
				errTimes = errTimes + 1;//本次错误追加1次
				//累计交易密码错误次数
				userInfo.setTradeErrTimes(errTimes) ;
				
				logger.info( "已错误"+errTimes+"次，还有"+(BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES-errTimes)+"次机会将被锁定！" );
				if(errTimes >= BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES){
					//错误次数超限
					logger.warn("user<"+userId+"> trade password lock");
					userInfo.setFaStatus("04");
				}
				userService.updateUser(userInfo);

				result.setAttribute("remainingErrorNumber", BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES-errTimes);
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4011);
				result.setMessage("交易密码不正确");
				return result;
			}
			
			//检查如果用户的交易密码累计次数大于0，则重置为0，因为本次输入正确了
			if(userInfo.getTradeErrTimes()>0){
				userInfo.setTradeErrTimes(0l);
				userService.updateUser(userInfo);
			}*/
				
			//成功通过校验
			if( logger.isInfoEnabled() ){
				logger.info("sendPayRequestBZJ request paymentBaofooBizService!");
			}	

			//支付请求参数
			Map<String, String> payRequest = new HashMap<String, String>();
			payRequest.put("orderid", orderId);//订单编码
			payRequest.put("identityid", userId.toString());//用户唯一编码
			payRequest.put("smsCode", smsCode);//2016-01-18添加短信
			payRequest.put("cardId", cardId);//卡id

			//发送短信请求
			Map<String,String> resultMap = new HashMap<String,String>();
			resultMap = paymentBaofooBizService.sendPayRequestBZJ(payRequest);
			if("SUCCESS".equals(resultMap.get("status"))){
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				
				//返回-支付金额、支付内容、支付金额、支付方式、交易时间、交易单号
				result.setAttribute("amount", resultMap.get("amount"));
				result.setAttribute("content", resultMap.get("content"));
				result.setAttribute("mode", resultMap.get("mode"));
				result.setAttribute("time", resultMap.get("time"));
				result.setAttribute("number", resultMap.get("number"));
				
				if( logger.isInfoEnabled() ){
					logger.info("sendPayRequestBZJ request paymentBaofooBizService SUCCESS!");
				}
				
				try{
					/*支付请求成功 发送短信通知 */
					List<String> mobile=new ArrayList<String>();
					mobile.add(userInfo.getLoginName());
					
					String content="您尾号%s的卡片 %s支付保证金 RMB%s元，如有问题请拨打电话400-855-8085";
					content=String.format(content,StringUtil.encryptCardNumberPostFour(resultMap.get("cardNumber")),DateUtil.getString(new Date(),"HH:mm"),resultMap.get("amount"));
					
					smsNewService.sendSms(mobile,content,"smsSendSwitch");
					/*支付请求成功 发送短信通知   金融产品部 */
					List<String> mobileList=new ArrayList<String>();
					for (String phone : biddingProductPhoneTo.split(";")) {
						if(!StringUtils.isBlank(phone.trim()))
							mobileList.add(phone);
					}
					UserDTO user=SessionUtil.getSession().getUser();
					//发送短信和邮件
					String contents="%s用户竞价【%s】产品，该用户手机号码%s，请及时审核";
					String realName = user.getuRealName();
					String loginName = user.getLoginName();
					contents=String.format(contents, StringUtils.isBlank(realName)?loginName:realName,resultMap.get("productName"),loginName);
					smsNewService.sendSms(mobileList,contents,"smsSendSwitch");
					
					//发送邮件
					MailContentDTO mail = new MailContentDTO();
					mail.setRecAddress( biddingProductEmailTo);
					mail.setCc( biddingProductEmailCopyTo);
					mail.setSubject("用户竞价产品");
					mail.setContext(contents);
					mailSenderService.send(mail);
				} catch (Exception e) {
					log.error("上传产品发送短信,邮件异常",e);
				}
				
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("errorMsg", resultMap.get("errorMsg"));
				
				if( logger.isInfoEnabled() ){
					logger.info("sendPayRequestBZJ request paymentBaofooBizService FAILE!");
				}
			}

			
		} catch (Exception e) {
			log.error("sendPayRequestBZJ error!",e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	
	/**
	 * 用户发送提现请求
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return 
	 * {
	 * retCode=1
	 * retMessage=""
	 * needJump=""
	 * }
	 */
	@RequestMapping("/withdrawals")
	@ResponseBody
	public synchronized ResultMap withdrawals(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();

		if( logger.isInfoEnabled() ){
			logger.info("withdrawals request begin!");
		}
		
		try {
			
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			String userId = loginUser.getId();
			
			//获取前端传入的数据。手机号、用户编号。
			String tradePwd = request.getParameter("tradePwd");//交易密码
			String youDanAmountDetailId = request.getParameter("youDanAmountDetailId");//提现业务id
			String cardId = request.getParameter("cardId");//卡id
			Integer cardId_ = null;
			Integer youDanAmountDetailId_ = null;
			String payPlat = BizEnums.PayEnums.PAY_3PLAT_BAOFOO;//默认-支付厂商标识（宝付）
			Date now = new Date();
			
			//检查参数是否有空值
			if(BasicUtils.isEmpty(youDanAmountDetailId,cardId)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			try {
				cardId_ =  Integer.valueOf(cardId);
				youDanAmountDetailId_ =  Integer.valueOf(youDanAmountDetailId);
			} catch (Exception e) {
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			if(BasicUtils.isEmpty(tradePwd) || userId== null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			
			//2、，检查用户状态
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			if(StringUtils.isEmpty(userInfo.getTradePwd())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4008);
				result.setMessage("交易密码不存在");
				return result;
			}
			
			
		
			if(StringUtils.isEmpty(userInfo.getDefBingingCrad())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4007);
				result.setMessage("还未绑定银行卡");
				return result;
			}
			//TODO 3、判断用户状态
			
			
			//4, 检查用户输入的交易密码是否正确
			if(!StringUtils.equals(userInfo.getTradePwd(), SecureUtil.MD5EncryptAndBase64(tradePwd)) ){
				long errTimes = userInfo.getTradeErrTimes();//输入的交易密码错误次数
				errTimes = errTimes + 1;//本次错误追加1次
				//累计交易密码错误次数
				userInfo.setTradeErrTimes(errTimes) ;
				
				logger.info( "已错误"+errTimes+"次，还有"+(BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES-errTimes)+"次机会将被锁定！" );
				if(errTimes >= BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES){
					//错误次数超限
					logger.warn("user<"+userId+"> trade password lock");
					userInfo.setFaStatus("04");
				}
				userService.updateUser(userInfo);

				result.setAttribute("remainingErrorNumber", BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES-errTimes);
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4011);
				result.setMessage("交易密码不正确");
				return result;
			}
			
			//检查如果用户的交易密码累计次数大于0，则重置为0，因为本次输入正确了
			if(userInfo.getTradeErrTimes()>0){
				userInfo.setTradeErrTimes(0l);
				userService.updateUser(userInfo);
			}

			
				
			//提现状态验证
			FpYouDanAmountDetailDTO youDanAmountDetailDTO  = youDanAmountDetailServiceImpl.queryYouDanAmountDetailById(youDanAmountDetailId_);
			String orderId = null;
			
			if(youDanAmountDetailDTO ==  null ){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("业务对象不存在");
				return result;
			}
			
			/* 02:可提现 状态  05:可提现 失败  */
			if(!BizEnums.YouDanAmountDetaiEnums.OPERATE_TYPE_KTX.equals(youDanAmountDetailDTO.getOperateType())
				&& !BizEnums.YouDanAmountDetaiEnums.OPERATE_TYPE_SB.equals(youDanAmountDetailDTO.getOperateType())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				result.setMessage("违法操作");
				return result;
			}
			String amountType = null;
		    String amountTypeName = null;
		    
		    //提现-保证金
			if(BizEnums.YouDanAmountDetaiEnums.AMOUNT_TYPE_BZJ.equals(youDanAmountDetailDTO.getAmountType()) ){
				amountType = BizEnums.PayEnums.PAY_INTERFACE_TYPE_TXBZJ;
				
				
				//获取保证金 code
				FpBiddingReceiptDTO dto = new FpBiddingReceiptDTO();
				dto.setId(Integer.parseInt(youDanAmountDetailDTO.getAssociationId()));
				dto = fpBiddingReceiptService.queryFpBiddingReceiptInfo(dto);
				if(dto ==  null ){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					result.setMessage("业务对象不存在");
					return result;
				}
				
				ProductDetailPageDTO product = productService.getProductDetailPage(dto.getpId());
				amountTypeName = product.getProductShortName();
				
				orderId = dto.getBiddingCode();
			}
			
			//提现-佣金
			if(BizEnums.YouDanAmountDetaiEnums.AMOUNT_TYPE_YJ.equals(youDanAmountDetailDTO.getAmountType()) ){
				amountType = BizEnums.PayEnums.PAY_INTERFACE_TYPE_TXYJ;
				
				
				//获取订单 code
				OrderDTO orderDTO = orderService.getOrder(youDanAmountDetailDTO.getAssociationId());
				if(orderDTO ==  null ){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					result.setMessage("业务对象不存在");
					return result;
				}
				amountTypeName = orderDTO.getpName();
				orderId = orderDTO.getOrderCode();
			}
			
			//发送提现请求
			//查询用户银行卡
			BankCardDTO bankCardDTO  = new BankCardDTO();
			bankCardDTO.setId(cardId_);
			bankCardDTO.setUserId(userId);
			bankCardDTO = bankCardServiceImpl.queryBankCard(bankCardDTO);
			
			if(bankCardDTO==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4007);
				return result;
			}
			
			//银行卡
			String bankCard = bankCardDTO.getCardNumber();
			
			//调用 提现 登记到 FpPaymentDTO支付流水表中，便于日后对账使用 ，用“接口类型”区别开
			
			FpPaymentDTO payment = new FpPaymentDTO();
			payment.setPayId(youDanAmountDetailId);//每笔订单一个支付流水，因此可重用ID
			payment.setPlatSerialNo(BasicUtils.genPlatSerialNoSimple(
					payPlat));//平台流水号(加上支付商标识)
			payment.setOrderId(orderId);//订单编码
			payment.setInterfaceType(amountType);//支付
			payment.setPayDate(sd.format(now));//支付日期
			payment.setPayStartTime(now);
			payment.setPayAmt(youDanAmountDetailDTO.getAmount());//支付金额 = 提现总金额
			payment.setCurCode(BizEnums.CommonEnums.MONEY_TYPE_RMB);//默认人民币
			payment.setOutAccount(BizEnums.CommonEnums.SUPERFA_FUND_ACCOUNT_NO);//资金存入账户 （超级理财师指定账户）
			payment.setInAccount(bankCard);//资金扣出账户（用户个人账户）
			payment.setPayStatus(BizEnums.PayEnums.PAY_STATUS_NEW);//支付状态 待支付
			payment.setTpay3plat(payPlat);//支付商标识
			payment.setPayDesc(amountTypeName);//支付描述
			payment.setCardCarrier(bankCardDTO.getUserName());//持卡人姓名
			payment.setUserId(userId);//用户id
			payment.setCardNo(bankCard);//持卡号
			payment.setPayMode(bankCardDTO.getBankName());//交易方式
			payment.setPayType("offline");//支付类型（online,offline）
			DTOdateSetUtil.setCreateInfo(payment);
			DTOdateSetUtil.setUpdateInfo(payment);
			
			
			//更新有单金额明细表  OPERATE_TYPE 03：提现中
			youDanAmountDetailDTO.setOperateType(BizEnums.YouDanAmountDetaiEnums.OPERATE_TYPE_TXZ);
			//更新提现时间
			youDanAmountDetailDTO.setWithdrawDate(new Date());
			//对应支付流水号
			youDanAmountDetailDTO.setPlatSerialNo(payment.getPlatSerialNo());
			//对应的银行卡ID
			youDanAmountDetailDTO.setCardId(bankCardDTO.getId());
			
			if( logger.isInfoEnabled() ){
				logger.info("withdrawals request commonServiceImpl db!");
			}
			String resultString =  commonServiceImpl.withdrawalsDealSuccessNew(payment, youDanAmountDetailDTO);
			if("SUCCESS".equals(resultString)){
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("payMode", new StringBuffer().append(payment.getPayMode()).append("(").append(StringUtil.encryptCardNumberPostFour(payment.getCardNo())).append(")").toString());
				result.setAttribute("payAmt", youDanAmountDetailDTO.getAmount());
				
				if( logger.isInfoEnabled() ){
					logger.info("withdrawals request commonServiceImpl db SUCCESS!");
				}
				
				
				try {
					//TODO 发送短信
					String userName=bankCardDTO.getUserName();
					BigDecimal amount = youDanAmountDetailDTO.getAmount();
					List<String> mobileList=new ArrayList<String>();
					for (String phone : withdrawalsPhoneTo.split(";")) {
						if(!StringUtils.isBlank(phone.trim()))
							mobileList.add(phone);
					}
					//发送短信和邮件
					String content="用户【%s】申请提现，金额【%s】,请及时处理";
					content=String.format(content, userName,amount.doubleValue());
					smsNewService.sendSms(mobileList,content,"smsSendSwitch");
					
					//发送邮件
					MailContentDTO mail = new MailContentDTO();
					mail.setRecAddress(withdrawalsEmailTo);
					mail.setCc(withdrawalsEmailCopyTo);
					mail.setSubject("用户申请提现");
					mail.setContext(content);
					mailSenderService.send(mail);
				} catch (Exception e) {
					log.error("用户申请提现发送短信,邮件异常",e);
				}
				
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4015);
				
				if( logger.isInfoEnabled() ){
					logger.info("withdrawals request commonServiceImpl db FAILE!");
				}
			}

			
		} catch (Exception e) {
			log.error("withdrawals error!",e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
}
